﻿package com.login;

import java.io.BufferedReader;
import java.io.BufferedWriter;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Scanner;

import com.core.Novel;
import com.core.User;
import com.util.Datas;
import com.util.NovelStyle;
import com.util.SysConstants;

public class Client {
	  static  Socket socket = null;//创建socket实例
	  static ObjectInputStream ois = null;//创建对象输入流实例
	  static   ObjectOutputStream oos = null;//创建对象输出流实例
	  
	static  Scanner input = new Scanner(System.in);
	static  Novel novel = new Novel();
	/**
	 * 初始化输入对象
	 */
	  public void  initSocket(){
		 try {
			Socket socket = new Socket("localhost",8800);
			 //接收服务器的数据流
			 ois= new ObjectInputStream(socket.getInputStream());
			 //向服务器发出数据流
			 oos = new ObjectOutputStream(socket.getOutputStream());
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	  }
	     public static void closeSocket(){
	    try{	 oos.close();
	    	 ois.close();
	    	 socket.close();
	     }catch(IOException e){
	    	 e.getStackTrace();
	     }
	     }
	  /**
	   * main方法
	   */
	  public static void main(String[] args) {
		 new Client().initSocket();
		 LovinView();
	}
	         
	
	public static void LovinView() {
		int num = 0;
	
		while(true){
		System.out.println("欢迎使用在线迷你TXT小说管理器");
		System.out.println("-----------------------------------");
		System.out.println("1.登录\n2.注册\n3.退出");
		System.out.println("------------------------------------");
		System.out.println("请选择(1/2/3):");
	 try{
		   input = new Scanner(System.in);
		   num = input.nextInt();
	 }catch(Exception e){
		 System.err.println("请输入整数！");
		 
	 }
		  if(num==1){
			//调用登录方法
			Login();
		}else if(num==2){
			Register();
		}
		else if(num==3){
			
			System.exit(1);
		}else if(num!=1&&num!=2&&num!=3){
			System.err.println("输入有误，请重新输入！");
			continue;
		}
	
	}
		}
	
	
	/**
	 * 登录操作
	 */
	public static void Login(){
		 System.out.println("============================");
		System.out.println("当前操作：用户登录");
		System.out.println("=============================");
		System.out.print("请输入登录名：");
		String LoginName=input.next();
		System.out.print("请输入登录密码：");
		String LoginPassword=input.next();
		System.out.println("*******************************");
		Datas datas=new Datas();
		User user=new User();
		user.setUserName(LoginName);
		user.setUserPassword(LoginPassword);
		
		datas.setFlag(SysConstants.SYS_LOGIN);
		datas.setUser(user);
		
		try {
			oos.writeObject(datas);
			datas=(Datas) ois.readObject();
			
			if(datas.getFlag().equals(SysConstants.SYS_SUCCESS)){
				System.out.println("登录成功");
				novelIndex();
				
			}
			else if(datas.getFlag().equals(SysConstants.SYS_ERROR))
			{
				System.err.println("登录失败，请检查登录名和密码，重新登录");
              //重新登录
				LovinView();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			closeSocket();
		}
		
	}
	
	
	/**
	 * 注册
	 */
	public static void Register(){
		System.out.println("当前操作：用户注册");
		 System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~");
		System.out.print("请输入登录名：");
		String LoginName=input.next();
		System.out.print("请输入登录密码：");
		String LoginPassword=input.next();
		System.out.print("请再次输入登录密码：");
		String LoginPasswordAgain=input.next();
		
		User user=new User();
		Datas datas=new Datas();
		user.setUserName(LoginName);
		user.setUserPassword(LoginPassword);
		
		datas.setFlag(SysConstants.SYS_REGISTER);
		datas.setUser(user);
		
		try{
			oos.writeObject(datas);				
			datas =(Datas) ois.readObject();
		}catch(Exception e){
			System.out.println(e.getMessage());
		}finally{
			
		}
		
		
		if(datas.getFlag().equals(SysConstants.SYS_SUCCESS)&&LoginPassword.equals(LoginPasswordAgain)){
			System.out.println("注册成功");
		    Login();			
		}
		else if(!LoginPassword.equals(LoginPasswordAgain)){
			System.err.println("两次输入的密码不一致，重新注册");
			Register();
		}
		else{
			System.err.println("用户名已存在，重新注册");
			Register();
		}
	  
	}
	
	
	/**
	 * 小说类型列表
	 */
	public static void novelIndex() throws Exception{
		int press=0;// 用于表明选择了什么操作
		
		System.out.println("------------------------------");
		System.out.println("0.返回上级菜单");
		System.out.println("1.武侠");
		System.out.println("2.言情");
		System.out.println("------------------------------");
		System.out.println("请选择：");
		press = input.nextInt();
		if(press==0){
			Login();
		}
		else if(press==1){
			NovelList(NovelStyle.WuXia);
		}
		else if(press==2){
			NovelList(NovelStyle.YanQing);
		}
		else{
			System.err.println("输入错误！重新输入");
			novelIndex();
		}
			
	}
	
	
	
	/**
	 * 小说列表
	 */
	public static void NovelList(NovelStyle noveltype) throws Exception{	
		String str = "";
		ArrayList<Novel> list = new ArrayList<Novel>();		
		Datas datas=new Datas();	
		datas.setFlag(SysConstants.SYS_NOVELLIST);
		if(noveltype.equals(NovelStyle.WuXia)){
			datas.setFlagList(SysConstants.SYS_NOVELSTYLE1);
			datas.setNovelstyle(NovelStyle.WuXia);
			str = "武侠小说列表";
		}
		else if(noveltype.equals(NovelStyle.YanQing)){
			datas.setFlagList(SysConstants.SYS_NOVELSTYLE2);
			datas.setNovelstyle(NovelStyle.YanQing);
			str="言情小说列表";
		}
		System.out.println("--------------" + str + "-------------");
									
		if(datas.getNovelstyle().equals(noveltype)){  
			oos.writeObject(datas);			
		    datas = (Datas) ois.readObject();	
			System.out.println("序号\t\t名称\t\t作者\t\t\t\t简介");			
			list = (ArrayList<Novel>)datas.getNovelList();
			for (int i = 1;i <= list.size();i++) {					 					
				System.out.println(i + ".\t\t"
						+ list.get(i-1).getName() + "\t\t"
						+ list.get(i-1).getAuthor() + "\t\t\t"
						+ list.get(i-1).getDescription());
			}
		} else {
			System.out.println("服务器无此类小说");
		}
				
				
		System.out.println("--------------小说列表结束-------------");
		System.out.println("阅读和下载请选择文件序号，上传TXT输入-1，返回输入0：");
		// 获取输入跳转到各自功能
		int press = input.nextInt();
		switch (press) {
		case -1:
			UpLoad(noveltype);
			break;
		case 0:
			novelIndex();
			break;
		default:
			novel = list.get(press - 1);
			datas.setNovel(novel);
			datas.setNovelstyle(noveltype);
			readNovelOptions(datas);						
			break;
		}
		
	}
	
	
	/**
	 * 上传小说
	 */

	public static void UpLoad(NovelStyle noveltype) throws Exception{
		 Novel novel=new Novel();
		 Datas datas =new Datas();
		 datas.setFlagList(noveltype.toString());
		 System.out.println("请输入小说名：");
		 String NovelName=input.next();
		 System.out.println("请输入作者：");
		 String NovelAuthor=input.next();
		 System.out.println("请输入简介：");
		 String Description=input.next();
		 
		 novel.setName(NovelName);
		 novel.setAuthor(NovelAuthor);
		 novel.setDescription(Description);		 
		 datas.setFlag(SysConstants.SYS_UPLOAD);
		 novel.setNovelstyle(noveltype);
		 datas.setNovel(novel);
		 
		
		 ArrayList<Novel> novelList = new ArrayList<Novel>();
		 novelList.add(novel);
		 datas.setNovelList(novelList);
		 System.out.print("请输入上传的txt（请注意路径用/或者\\）：");
		 String path=input.next();
		 System.out.println("************************************");
		 
		 String TXTContent="";
		 String temp="";
		 FileReader fr=null;
		 try{
		 fr=new FileReader(path);
		 BufferedReader br=new BufferedReader(fr);
		 if((temp=br.readLine())!=null){
			TXTContent=TXTContent+temp;
		 }
		 br.close();
		 fr.close();
		 datas.setTXTContents(TXTContent);
		 
	
		 oos.writeObject(datas);		
		 datas=(Datas)ois.readObject();
		 
		 }catch(Exception ex){
		    System.out.println(ex.getMessage());
		 }
		 
		 if(datas.getFlag().equals(SysConstants.SYS_SUCCESS)){
				System.out.println("小说保存成功");
				System.out.println("**************************");
			}
			
		 
		 System.out.println("继续上传请输入1，返回请输入0：");
		 int spress=input.nextInt();
		 if(spress==1){			
			 UpLoad(novel.getNovelstyle());
		 }
		 else if(spress==0){
			 novelIndex();
		 }
		 else
			 System.err.println("输入有误！");
			
			
	}
	
	
	
	/**
	 * 阅读索引
	 */
	public static void readNovelOptions(Datas datas) throws Exception{
		System.out.println("------------------------------");
		System.out.println("0.返回上一级菜单");
		System.out.println("1.在线阅读");
		System.out.println("2.下载TXT");
		System.out.println("------------------------------");
		System.out.println("请选择：");
		int mark = input.nextInt();
		if(mark==0){
	
			novelIndex();
		}
		else if(mark==1){
			ReadNovel();
		}
		else if(mark==2){
			
			DownLoad(datas);
		}
	}
	
	/**
	 * 读小说
	 */
	public static void ReadNovel() throws Exception{
		Datas datas=new Datas();
		datas.setFlag(SysConstants.SYS_READNOVEL);
		datas.setNovel(novel);
		
		oos.writeObject(datas);
		datas=(Datas) ois.readObject();
		System.out.println("当前阅读:"+novel.getName());
						
		System.out.println(datas.getTXTContents());
		
		
		
		System.out.println("1.返回列表输入1，继续阅读请下载输入2：");
			
		int press = input.nextInt();
		if(press==1){
			novelIndex();
	
		}
		else if(press==2){
			DownLoad(datas);
		}
		else
			System.out.println("输入错误！");
		
		
	}
	
	/**
	 * 下载
	 */
	public static void DownLoad(Datas datas){

		datas.setFlag(SysConstants.SYS_DOWNLOAD);
		
	  try{
		  
		datas.setNovel(datas.getNovel());
		oos.writeObject(datas);
		datas = (Datas) ois.readObject();
		
		System.out.println("******************************");
		System.out.print("下载后的文件名是：");
		String fileName =novel.getName()+".txt";
		System.out.println(fileName);
		System.out.print("下载后的路径是：");
		String filePath=input.next();
		
		
	
		FileWriter fw = null;
		BufferedWriter bw = null;
		FileReader fr=null;
		BufferedReader br=null;
		//找到正确路径下载指定的文本当中
		fw = new FileWriter(filePath +"/"+fileName);
		bw = new BufferedWriter(fw);
		bw.write(datas.getTXTContents());
		bw.flush();//刷新！
		fr=new FileReader(filePath+"/"+fileName);
		br=new BufferedReader(fr);
		if(br.readLine()!=null){
			System.out.println("文件下载结果：true");
		  }
		
		br.close();			
	    fr.close();
	    bw.close();
	    fw.close();
	    
	    System.out.println("返回输入0：退出输入-1：");
	    int spress=input.nextInt();
	    if(spress==0){
	    	novelIndex();
	    }
	    else if(spress==-1){
	    	System.exit(1);
	    }	    	    	    
	    else{
	    	System.out.println("输入错误！");
	    }
		
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
		
	}
	

}
	